<template>
  <div class="login">
    <validate-form @form-submit="onSubmit">
      <label for="email" class="form-label">邮件地址</label>
      <validate-input
        id="email"
        v-model="email"
        :rules="emailRules"
        placeholder="email"
      />
      <label for="password" class="form-label">密码</label>
      <validate-input
        id="password"
        type="password"
        v-model="password"
        :rules="passwordRules"
        placeholder="password"
      />
      <template #submit>
        <button type="submit" class="btn btn-primary">登录</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import ValidateForm, { TValidateFn } from "@/components/ValidateForm.vue";
import ValidateInput, { RulesProp } from "@/components/ValidateInput.vue";
import { useRouter } from "vue-router";
import { useStore } from "@/store";

export default defineComponent({
  setup() {
    const email = ref<string>("admin@itiger.com");
    const password = ref<string>("qqqqqqq1");

    const emailRules: RulesProp = [
      { type: "required", message: "请输入邮箱地址" },
      { type: "email", message: "请输入合法邮箱地址" },
    ];
    const passwordRules: RulesProp = [
      { type: "required", message: "请输入密码" },
    ];

    const router = useRouter();
    const store = useStore();

    const onSubmit = (results: ReturnType<TValidateFn>[]) => {
      if (!results.includes(false)) {
        store
          .dispatch({
            type: "login",
            email: email.value,
            password: password.value,
          })
          .then(() => {
            router.push({ name: "home" });
          });
      }
    };

    return {
      email,
      password,
      emailRules,
      passwordRules,
      onSubmit,
    };
  },
  components: { ValidateForm, ValidateInput },
});
</script>

<style lang="less" scoped>
.login {
  width: 400px;
  margin: 20px auto;
}
</style>
